<template>
    <a-drawer class="container" :visible="visible" :title="props.title" :width="520" @close="handleClose">
        <a-spin :spinning="loading">
            <a-form ref="refForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-form-item name="dictTypeId" label="字典类型">
                    <a-select v-model:value="form.dictTypeId" placeholder="请选择字典类型" allow-clear :options="dictTypeDictList" />
                </a-form-item>
                <a-form-item name="code" label="编码">
                    <a-input v-model:value="form.code" placeholder="请输入编码" allow-clear />
                </a-form-item>
                <a-form-item name="name" label="名称">
                    <a-input v-model:value="form.name" placeholder="请输入名称" allow-clear />
                </a-form-item>
                <a-form-item name="orderIndex" label="显示顺序">
                    <a-input-number v-model:value="form.orderIndex" placeholder="请输入显示顺序" style="width: 100%" :min="1" :max="999" />
                </a-form-item>
                <a-form-item name="description" label="描述">
                    <a-input v-model:value="form.description" placeholder="请输入描述" allow-clear />
                </a-form-item>
            </a-form>
            <a-divider />
            <div>
                <a-button type="primary" @click="handleConfirm">确定</a-button>
                <a-button style="margin-left: 16px" @click="handleClose">取消</a-button>
                <a-button style="margin-left: 16px" @click="handleReset">重置</a-button>
            </div>
        </a-spin>
    </a-drawer>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
// Api
import Api from '@/axios/api/sys/dict';
// Component
import { message } from 'ant-design-vue';
// Model
import { Dict, DictType, Result } from '@/model/common';
import { DictForm, DictDTO } from '@/model/sys/dict';
// Plugin
import { Bus, BusEvent } from '@/plugin';
// Util
import { DictUtil, ObjectUtil } from '@/util';

// 参数
const props = defineProps({
    visible: {
        type: Boolean,
        default: false,
    },
    title: {
        type: String,
        default: '编辑字典数据',
    },
});

// 变量
const visible = ref<boolean>(false);
const loading = ref<boolean>(false);
const labelCol = { span: 4 };
const wrapperCol = { span: 18 };
const refForm = ref();
const form = ref<DictForm>(new DictForm());
const rules = DictForm.rules;
const dictTypeDictList = ref<Dict[]>([]);

// 新增标识，为false时表示更新
const insertFlag = ref<boolean>(false);
// 数据变化标识，为true时需要发送更新列表的消息
const dataChangedFlag = ref<boolean>(false);

// 方法
onMounted(() => {
    init();
});

const init = () => {
    loadDict();
};

/**
 * 打开编辑页面
 */
const open = (id: string | undefined) => {
    if (id) {
        loadInfo(id);
        insertFlag.value = false;
    } else {
        insertFlag.value = true;
    }
    visible.value = true;
};

/**
 * 关闭编辑页面
 */
const close = () => {
    visible.value = false;
};

/**
 * 页面关闭时的回调
 */
const handleClose = () => {
    close();
    if (!insertFlag.value) {
        handleReset();
    }
    if (dataChangedFlag.value) {
        Bus.emit(BusEvent.REFRESH_DICT);
    }
    dataChangedFlag.value = false;
};

/**
 * 点击确认按钮事件
 */
const handleConfirm = () => {
    refForm.value.validate().then(() => {
        insertFlag.value ? insert() : update();
    });
};

/**
 * 重置表单
 */
const handleReset = () => {
    refForm.value.resetFields();
};

/**
 * 新增
 */
const insert = () => {
    loading.value = true;
    Api.insert(form.value)
        .then(() => {
            dataChangedFlag.value = true;
            message.success('新增成功。');
            handleReset();
        })
        .catch((err: Result) => {
            message.error(`新增失败。${err.msg}`);
        })
        .finally(() => {
            loading.value = false;
        });
};

/**
 * 修改
 */
const update = () => {
    loading.value = true;
    Api.update(form.value)
        .then(() => {
            dataChangedFlag.value = true;
            message.success('修改成功。');
            handleClose();
        })
        .catch((err: Result) => {
            message.error(`修改失败。${err.msg}`);
        })
        .finally(() => {
            loading.value = false;
        });
};

/**
 * 获取信息
 */
const loadInfo = (id: string) => {
    loading.value = true;
    Api.info(id)
        .then((res: Result) => {
            ObjectUtil.copy(res.data, form.value);
        })
        .finally(() => {
            loading.value = false;
        });
};

const loadDict = () => {
    DictUtil.get(DictType.DICT_TYPE).then((res) => (dictTypeDictList.value = res));
};

// 定义组件对外暴露的内容
defineExpose({
    open,
});
</script>

<style lang="less" scoped></style>
